package com.brillilab.service.logic.account;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.brillilab.common.constant.SystemConfigConstant;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.brillilab.common.entity.PageVo;
import com.brillilab.common.utils.DateUtil;
import com.brillilab.domain.enums.account.IntegralStateEnum;
import com.brillilab.domain.enums.account.IntegralTypeEnum;
import com.brillilab.domain.po.account.IntegralRecord;
import com.brillilab.domain.po.account.UserAccount;
import com.brillilab.domain.po.system.SystemConfig;
import com.brillilab.domain.vo.account.AccountDetailedVo;
import com.brillilab.domain.vo.system.RedEnvelopeRuleVo;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.core.account.IntegralRecordService;
import com.brillilab.service.core.account.UserAccountService;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.system.ISystemConfigService;
import com.brillilab.service.module.message.producer.MessageProducer;
import com.brillilab.service.module.message.template.impl.message.PushMessageTemplate;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@Transactional
public class UserAccountLogic {

	@Resource
	private ILabMemberService labMemberService;
	
	@Resource
	private IntegralRecordService integralRecordService;
	
	@Resource
	private UserAccountService userAccountService;
	
	@Resource
	private MessageProducer messageProducer;
	@Resource
	private ISystemConfigService systemConfigService;
	
	/**
	 * 新增用户积分记录
	 * @param userId
	 * @param integral
	 * @return
	 */
	public IntegralRecord addIntegral(UserInfoVo userInfo, IntegralTypeEnum integralType, Long dataId) {
		try {
			
			int integral = createIntegral(userInfo, integralType, dataId);
			if(integral>0) {
				IntegralRecord record = new IntegralRecord();
				record.setLabId(userInfo.getLabId());
				record.setLabMemberId(userInfo.getLabMemberId());
				record.setUserId(userInfo.getId());
				record.setType(integralType.getValue());
				record.setState(IntegralStateEnum.UNRECEIVED.getValue());
				record.setIntegral(integral);
				record.setDataId(dataId);
				record = integralRecordService.insert(record);
				
				JSONObject jsonData = new JSONObject();
				jsonData.put("recordId", record.getId());
				jsonData.put("type", 1);
				PushMessageTemplate pushMessageTemplate = new PushMessageTemplate(userInfo.getLabId(), 
						userInfo.getId(), userInfo.getLabMemberId(), "恭喜您，获得一个红包", jsonData.toJSONString());
				messageProducer.sendMessagePush(pushMessageTemplate);
				return record;
			}
		} catch (Exception e) {
			log.error(">>>>>>> 新增用户积分记录异常：", e);
		}
		return null;
		
	}
	
	/**
	 * 生成积分
	 * @param userInfo
	 * @param integralType
	 * @return 
	 */
	private int createIntegral(UserInfoVo userInfo, IntegralTypeEnum integralType,Long dataId) {
		int integral = 0; 
		//判断领取规则生成积分
		RedEnvelopeRuleVo ruleVo = this.reruleInfo(integralType);
		if(ruleVo==null) {
			return integral;
		}
		
		if(integralType.getValue().equals(IntegralTypeEnum.TOPIC.getValue())) {
			List<IntegralRecord> records =integralRecordService.getIntegralRecord(userInfo.getId(), IntegralTypeEnum.TOPIC);
			if(CollectionUtils.isNotEmpty(records)) {
				return integral;
			}
		} else if(integralType.getValue().equals(IntegralTypeEnum.PLAN.getValue())) {
			Date dayBegin = DateUtil.getBeginDayOfWeek();
			Date dayEnd = DateUtil.getEndDayOfWeek();
			List<IntegralRecord> recordList = integralRecordService.getIntegralRecord(userInfo.getId(), IntegralTypeEnum.PLAN, dayBegin, dayEnd);
			if(CollectionUtils.isNotEmpty(recordList)) {
				return integral;
			}
		} else if(integralType.getValue().equals(IntegralTypeEnum.EXPERIMENT.getValue())) {
			Date dayBegin = DateUtil.getDayBegin();
			Date dayEnd = DateUtil.getDayEnd();
			List<IntegralRecord> recordList = integralRecordService.getIntegralRecord(userInfo.getId(), IntegralTypeEnum.EXPERIMENT, dayBegin, dayEnd);
			if(CollectionUtils.isNotEmpty(recordList) && recordList.size()>=5) {
				return integral;
			}else {
				IntegralRecord record =integralRecordService.getIntegralRecord(userInfo.getId(), IntegralTypeEnum.EXPERIMENT, dataId);
				if(record!=null) {
					return integral;
				}
			}
		}

		integral = new Random().nextInt(ruleVo.getMax());
		if(integral<ruleVo.getMin()) {
			integral = ruleVo.getMin();
		}
		return integral;
	}
	
	public RedEnvelopeRuleVo reruleInfo(IntegralTypeEnum integralType){
        SystemConfig systemConfig = systemConfigService.selectByCode(SystemConfigConstant.RE_RULE);
        if(systemConfig!=null) {
        	List<RedEnvelopeRuleVo> reruleList = JSON.parseArray(systemConfig.getValue(),RedEnvelopeRuleVo.class);
        	if(CollectionUtils.isNotEmpty(reruleList)) {
        		Map<Integer, List<RedEnvelopeRuleVo>> reruleMap = reruleList.stream().collect(Collectors.groupingBy(RedEnvelopeRuleVo::getType));		
        		List<RedEnvelopeRuleVo> ruleList = reruleMap.get(integralType.getValue());
        		if(CollectionUtils.isNotEmpty(reruleList)) {
        			return ruleList.get(0);
        		}
        	}
        }
        return null;
    }
	
	/**
	 * 根据用户ID获取账户信息
	 * @param userId
	 * @return
	 */
	public UserAccount getByUserId(Long userId) {
		return userAccountService.getByUserId(userId);
	}
	
	
	/**
	 * 获取积分记录列表
	 * @param userId
	 * @param integralState
	 * @return
	 */
	public List<IntegralRecord> getIntegralRecord(Long userId, IntegralStateEnum integralState) {
		List<IntegralRecord> recordList = integralRecordService.getIntegralRecord(userId, integralState);
		if(CollectionUtils.isNotEmpty(recordList) && IntegralStateEnum.UNRECEIVED.getValue().equals(integralState.getValue())) {
			List<Long> invalidIds = new ArrayList<Long>();
			for (Iterator<IntegralRecord> iterator = recordList.iterator(); iterator.hasNext();) {
				IntegralRecord record = iterator.next();
				int dateDiff = DateUtil.getDiffDays(record.getCreateTime(), new Date());
				if(dateDiff>0) {
					invalidIds.add(record.getId());
					iterator.remove();
				}
			}
			integralRecordService.setInvalid(invalidIds);
		}
		return recordList;
	}
	
	
	/**
	 * 用户领取积分单条记录领取
	 * @param userId
	 * @return 领取状态：1领取成功，2已过期，3已被领取过
	 */
	public int receivedIntegral(Long userId,Long recordId) {
		return integralRecordService.receivedIntegral(userId, recordId);
	}
	
	/**
	 * 获取用户未领取积分
	 * @param userId
	 * @param integralState
	 * @return
	 */
	public int getUnreceivedIntegral(Long userId) {
		return integralRecordService.getUnreceivedIntegral(userId);
	}
	
	/**
	 * 用户积分兑换
	 * @param userId
	 * @param exchangeId 兑换码ID
	 * @return 返回可兑换积分数
	 */
	public int exchangeIntegral(Long userId,Long exchangeId) {
		int totalIntegral = userAccountService.exchangeIntegral(userId);
		if(totalIntegral>0) {
			integralRecordService.exchangeIntegral(userId,exchangeId);
		}
		return totalIntegral;
	}

	public PageVo<AccountDetailedVo> getAccountDetailed(Long userId,int pageNum, int pageSize) {
		return userAccountService.getAccountDetailed(userId, pageNum, pageSize);
	}
	
}
